package com.huahan.auth.security.component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mall.common.constant.ResultCode;
import com.mall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author dd

 */
@Component
@Slf4j
public class HuahanAccessDeniedHandler implements AccessDeniedHandler {

  @Resource
  private ObjectMapper objectMapper;

  @Override
  public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException {
    response.setContentType("application/json;charset=UTF-8");
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    PrintWriter writer = response.getWriter();
    log.info("AccessDeniedHandler 用户无权访问 [{}]", e.getMessage());
    objectMapper.writeValue(writer, R.error(ResultCode.PERMISSION_ACCESS_DENIED.getMessage()));
  }
}
